from PyQt5 import QtWidgets,QtGui,QtCore
from RecordSelectUI import Ui_SalaryRecordSelect
import sys
import sqlite3
import datetime

class SalaryRecordSelect(QtWidgets.QWidget,Ui_SalaryRecordSelect):
    def __init__(self,username='test',dbpath='test.db'):
        super(SalaryRecordSelect,self).__init__()
        self.setupUi(self)
        self.setuptableView()# init tableview

        self.username = username
        self.dbpath = dbpath
        self.setname() #init nameEditor
        self.setdate() #init start_date,end_date

        self.pushButton.clicked.connect(self.Query)
        
    def setname(self):
        self.name_label.setText(self.username) #init nameEditor
    def setdate(self):
        #init date
        self.start_date.setDate(datetime.date.today())
        self.end_date.setDate(datetime.date.today())
        
    def setuptableView(self):
        self.model = QtGui.QStandardItemModel(self.tableView)

        self.model.setRowCount(0)
        self.model.setColumnCount(4)
        self.model.setHorizontalHeaderLabels(['Date','Name','Salary','RecordTime'])

        #append row
        #item = QtGui.QStandardItem("row %s,column %s "%(row,column))
        #self.model.setItem(row,column,item)
        
        #self.model.appendRow([QtGui.QStandardItem("row %s ,column %s"%(11,11)),
        #                     QtGui.QStandardItem("row %s ,column %s"%(11,11)),
        #                     QtGui.QStandardItem("row %s ,column %s"%(11,11)),
        #                     QtGui.QStandardItem("row %s ,column %s"%(11,11))])

        #100% show
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)

        self.tableView.setModel(self.model)

    def Query(self):
        self.model.setRowCount(0) #init model
        
        conn = sqlite3.connect(self.dbpath)
        c = conn.cursor()
        c.execute("SELECT * FROM record WHERE name=?",[self.username])
        sqlquery = c.fetchall()
        for data in sqlquery:
            self.model.appendRow([QtGui.QStandardItem(data[0]), #date
                                  QtGui.QStandardItem(data[1]), #name
                                  QtGui.QStandardItem(str(data[2])), #salary
                                  QtGui.QStandardItem(data[3])  #recordtime
                                  ])
        c.close()
        conn.close()
        return
        
                                  
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    salaryrecord = SalaryRecordSelect(username='test',dbpath='test.db')
    salaryrecord.show()
    sys.exit(app.exec())
